<template>
  <div class="preview-container">
    <h3 class="preview-title">文件预览</h3>
    <div class="input-group">
      <input
          type="text"
          v-model="localFileName"
          placeholder="输入文件名"
          class="file-input"
      />
      <button @click="preview" class="preview-btn">预览</button>
    </div>

    <div v-if="fileUrl" class="file-viewer">
      <iframe
          v-if="isPdf"
          :src="fileUrl"
          width="100%"
          height="500px"
          class="pdf-iframe"
      ></iframe>
      <div v-else class="unsupported-file">
        <p>无法预览此文件类型，请下载后查看。</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    fileName: String
  },
  data() {
    return {
      localFileName: '', // 使用局部变量存储文件名
      fileUrl: null,
    };
  },
  computed: {
    isPdf() {
      return this.fileUrl && this.fileUrl.toLowerCase().endsWith('.pdf');
    },
  },
  created() {
    this.localFileName = this.fileName || ''; // 初始化局部文件名
    this.previewFile();
  },
  methods: {
    async previewFile() {
      try {
        const response = await axios.get(`http://localhost:8080/api/resources/preview`, {
          params: { fileName: this.localFileName },
          responseType: 'json',
        });
        if (response.status === 200) {
          this.fileUrl = response.data.fileUrl;
        } else {
          alert('预览失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('预览失败:', error);
        alert('预览失败');
      }
    },
  },
};
</script>

<style scoped>
.preview-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.preview-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.file-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.preview-btn {
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.preview-btn:hover {
  background-color: #2980b9;
}

.file-viewer {
  margin-top: 20px;
}

.pdf-iframe, .google-docs-iframe {
  border: none;
}

.unsupported-file {
  color: #e74c3c;
  text-align: center;
}
</style>